/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：OrderTimeoutConsumer.java
 * History:
 *         2019年7月21日: Initially created, CJH.
 */
package club.coderleague.ilsp.common.rocketmq.consumer;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import club.coderleague.ilsp.common.domain.enums.OrderCancelType;
import club.coderleague.ilsp.common.exception.MessageInfoException;
import club.coderleague.ilsp.service.orders.OrdersService;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 订单超时消息消费者
 * 
 * @author CJH
 */
@Component
public class OrderTimeoutConsumer extends BaseDefaultMQPushConsumer {
	
	/**
	 * 消费者组
	 */
	public final static String CONSUMER_GROUP = "ORDER_TIMEOUT_CONSUMER";
	
	/**
	 * 订阅主题
	 */
	public final static String TOPIC = "ORDER_TIMEOUT_TOPIC";
	
	/**
	 * 订单Service
	 */
	private @Autowired OrdersService ordersService;

	/**
	 * 构造方法。
	 */
	public OrderTimeoutConsumer() {
		super(CONSUMER_GROUP, TOPIC, OrderTimeoutTagsEnum.getTags());
	}
	
	/**
	 * 订阅主题标签
	 * 
	 * @author CJH
	 */
	@Getter
	@AllArgsConstructor
	public enum OrderTimeoutTagsEnum {
		
		/**
		 * 待确认
		 */
		CONFIRM("confirm", "待确认"),
		
		/**
		 * 已确认
		 */
		CONFIRMED("confirmed", "已确认");
		
		/**
		 * 标签
		 */
		private String tag;
		
		/**
		 * 描述
		 */
		private String text;
		
		/**
		 * 获取标签
		 * 
		 * @author CJH 2019年7月24日
		 * @return 标签
		 */
		public static String getTags() {
			List<String> tags = new ArrayList<>();
			for (OrderTimeoutTagsEnum orderTimeoutTagsEnum : OrderTimeoutTagsEnum.values()) {
				tags.add(orderTimeoutTagsEnum.getTag());
			}
			return StringUtils.join(tags, " || ");
		}
	}

	/**
	 * @see club.coderleague.ilsp.common.rocketmq.consumer.BaseDefaultMQPushConsumer#messageHandle(org.apache.rocketmq.common.message.MessageExt, org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext)
	 */
	@Override
	protected void messageHandle(MessageExt messageExt, ConsumeConcurrentlyContext consumeConcurrentlyContext)
			throws Exception {
		String orderidstr = new String(messageExt.getBody());
		Long orderid = Long.valueOf(orderidstr);
		try {
			if (OrderTimeoutTagsEnum.CONFIRM.getTag().equals(messageExt.getTags())) {
				// 待确认订单确认超时处理
				ordersService.updateCancelConfirmOrder(orderid, OrderCancelType.SYSTEM, "订单超时未确认");
			} else if (OrderTimeoutTagsEnum.CONFIRMED.getTag().equals(messageExt.getTags())) {
				// 已确认订单支付超时处理
				ordersService.updateCancelConfirmedOrder(orderid, OrderCancelType.SYSTEM, "订单超时未支付");
			}
		} catch (MessageInfoException e) {
		}
	}

}
